package org.zjt.chapter1.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-07-19 下午4:50
 * @see
 */
@Slf4j
public class AggregatorHttpServer extends AbstractHttpServer {


    public static void main(String[] args) {
        new AggregatorHttpServer().start(8080);
    }

    @Override
    public ChannelInitializer<NioSocketChannel> getChannelInitializer() {
        return new ChannelInitializer<NioSocketChannel>(){
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                // http 编解码
                pipeline.addLast(new HttpServerCodec());

                // 异常处理
                pipeline.addLast(new HttpServerExpectContinueHandler());

                pipeline.addLast(new HttpObjectAggregator(2121));

                pipeline.addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                        log.info(msg.uri());

                        ByteBuf byteBuf = Unpooled.wrappedBuffer("hello world".getBytes());
                        DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,byteBuf);

                        HttpHeaders headers = httpResponse.headers();
                        headers.add("Content-Type","text/plain");

                        // http body 字节数
                        headers.addInt("content-length",byteBuf.readableBytes());

                        // 告知请求方可以建立长连接
                        headers.add("Connection","keep-alive");

                        boolean keepAlive = HttpUtil.isKeepAlive(msg);
                        if (keepAlive){
                            ctx.writeAndFlush(httpResponse);
                        }else {
                            ctx.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
                        }
                    }
                });
            }
        };
    }
}
